package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.CustomerDao;
import com.aaa.vegetablemarketexpress.dao.ShopCustomerDao;
import com.aaa.vegetablemarketexpress.dao.ShopDao;
import com.aaa.vegetablemarketexpress.dao.UserDao;
import com.aaa.vegetablemarketexpress.entity.*;
import com.aaa.vegetablemarketexpress.service.ShopService;
import com.aaa.vegetablemarketexpress.util.CustomException;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @FileName: ShopServiceImpl
 * @Description: 店铺业务逻辑实现类
 * @Author: qxh
 * @CreateTime: 2025/9/10
 * @Version: 1.0.0
 */
@Service
public class ShopServiceImpl implements ShopService {

    @Resource
    private ShopDao shopDao;
    @Resource
    private HttpSession session;
    @Autowired
    private UserDao userDao;
    @Resource
    private ShopCustomerDao shopCustomerDao;
    @Resource
    private CustomerDao customerDao;
    /**
     * 根据店铺ID查询店铺信息
     * @param shopId
     * @return
     */
    @Override
    public Shop selectShopById(Long shopId) {
        return shopDao.selectShopById(shopId);
    }

    /**
     * 分页查询店铺列表
     * @param page
     * @return
     */
    @Override
    public PageInfo selectShopList(Page<Shop> page) {
        // 分页查询
        if(page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        PageHelper.startPage(page.getPageNo(), page.getPageSize());// 开始分页
        Shop data = page.getData();// 获取查询条件
        //获取当前登录用户ID
        Long userId = ((User) (session.getAttribute("userInfo"))).getUserId();
        if (userDao.checkIsAdmin(userId)>0){// 是管理员
            return new PageInfo<>(shopDao.selectShopList(data));
        }else {// 不是管理员
            return new PageInfo<>(shopDao.selectShopListBindCustomer(userId));
        }

    }

    /**
     * 添加店铺,同时添加店铺和客户关系到 biz_shop_customer表
     * @param shop
     * @return
     */
    @Override
    @Transactional// 开启事务, 保证数据一致性
    public Shop insertShop(Shop shop) {
        // 检查店铺名称是否唯一
        String uniqueCheck = checkShopNameUnique(shop);
        if ("1".equals(uniqueCheck)) {
            throw new CustomException(ResultStatus.FAILED.getStatusCode(), "店铺名称已存在");
        }

        // 设置默认值
        if (shop.getStatus() == null || shop.getStatus().isEmpty()) {
            shop.setStatus("0"); // 默认正常状态
        }
        if (shop.getAuditStatus() == null || shop.getAuditStatus().isEmpty()) {
            shop.setAuditStatus("0"); // 默认待审核状态
        }
        if (shop.getDelFlag() == null || shop.getDelFlag().isEmpty()) {
            shop.setDelFlag("0"); // 默认未删除
        }
        // 确保businessLicence字段不为null
        if (shop.getBusinessLicence() == null) {
            shop.setBusinessLicence(""); // 设置为空字符串
        }
        shop.setCreateTime(new Date());
        shop.setUpdateTime(new Date());
        // 获取当前登录用户ID
        Long userId = ((User) (session.getAttribute("userInfo"))).getUserId();
        // 获取当前登录用户的昵称
        String nickNameByUserId = userDao.selectNickNameByUserId(userId);
        shop.setCreateBy(nickNameByUserId);
        shopDao.insertShop(shop);// 添加店铺shop
        Long customerIdByUserId = shopDao.queryCustomerIdByUserId(userId);// 根据用户ID查询客户ID customerId
        ShopCustomer shopCustomer = new ShopCustomer(null, shop.getShopId(), customerIdByUserId, new Date());// 创建店铺和客户关系对象shop_customer
        shopCustomerDao.insertShopCustomer(shopCustomer);// 添加店铺和客户关系
        return shop;
    }
    /**
     * 修改店铺
     * @param shop
     * @return
     */
    @Override
    public int updateShop(Shop shop) {
        // 验证店铺ID是否存在
        if (shop.getShopId() == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "店铺ID不能为空");
        }
        // 验证店铺是否存在
        Shop existingShop = shopDao.selectShopById(shop.getShopId());
        if (existingShop == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "店铺不存在");
        }
        shop.setUpdateTime(new Date());
        // 确保创建时间不被修改
        shop.setCreateTime(existingShop.getCreateTime());
        shop.setCreateBy(existingShop.getCreateBy());
        return shopDao.updateShop(shop);
    }

    /**
     * 删除店铺（逻辑删除）,同时删除店铺和客户关系
     * @param shopId
     * @return
     */
    @Override
    @Transactional
    public int deleteShopById(Long shopId) {
        shopCustomerDao.deleteShopCustomerByShopId(shopId);//根据店铺ID删除店铺和客户关系
        return shopDao.deleteShopById(shopId);
    }

    /**
     * 检查店铺名称是否唯一
     * @param shop
     * @return
     */
    @Override
    public String checkShopNameUnique(Shop shop) {
        int count = shopDao.checkShopNameUnique(shop.getShopName());
        if (count > 0) {
            return "1"; // 已存在
        }
        return "0"; // 不存在
    }

    /**
     * 审核店铺
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public int auditShop(Shop shop) {
        // 验证店铺ID是否存在
        if (shop.getShopId() == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "店铺ID不能为空");
        }
        // 验证店铺是否存在
        Shop existingShop = shopDao.selectShopById(shop.getShopId());
        if (existingShop == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "店铺不存在");
        }
        User userInfo = (User) session.getAttribute("userInfo");
        if (userInfo == null) {
            throw new CustomException(ResultStatus.USER_NOT_LOGIN.getStatusCode(), "审核人未登录，请重新登录");
        }
        // 更新审核相关信息
        Shop updateShop = new Shop();
        updateShop.setShopId(shop.getShopId());
        updateShop.setAuditStatus(shop.getAuditStatus());// 前端传递的审核结果（1通过/2拒绝）
        updateShop.setAuditRemark(shop.getAuditRemark());// 前端传递的审核备注
        shop.setAuditBy(userInfo.getUserName());// 从Session获取登录人姓名（审核人）
        shop.setAuditTime(new Date());// 自动生成当前审核时间
        shop.setUpdateTime(new Date());// 更新时间同步
        shopDao.updateShop(shop);

        // 如果审核通过，更新店铺状态为正常
        if ("1".equals(shop.getAuditStatus())) {
            updateShop.setStatus("0");
        }

        return shopDao.updateShop(updateShop);
    }

    /**
     * 根据用户ID查询店铺
     * @param userId
     * @return
     */
    /**
     * 根据用户ID获取店铺信息
     * @param userId
     * @return
     */
    @Override
    public Shop getShopByUserId(Long userId) {
        if (userId == null) {
            return null;
        }

        // 1. 通过userId查询对应的Customer
        Customer customerQuery = new Customer();
        customerQuery.setUserId(userId);
        List<Customer> customers = customerDao.selectCustomerList(customerQuery);
        if (CollectionUtils.isEmpty(customers)) {
            return null;
        }
        Long customerId = customers.get(0).getCustomerId();

        // 2. 通过customerId查询ShopCustomer关联记录
        ShopCustomer shopCustomerQuery = new ShopCustomer();
        shopCustomerQuery.setCustomerId(customerId);

        List<ShopCustomer> shopCustomers = shopCustomerDao.selectShopCustomerList(customerId);
        if (CollectionUtils.isEmpty(shopCustomers)) {
            return null;
        }
        Long shopId = shopCustomers.get(0).getShopId();

        // 3. 通过shopId查询店铺信息
        Shop queryShop = new Shop();
        queryShop.setShopId(shopId);
        List<Shop> shops = shopDao.selectShopList(queryShop);
        return CollectionUtils.isEmpty(shops) ? null : shops.get(0);
    }

    /**
     * 店铺审核成功列表
     * @param page
     * @return
     */
    @Override
    public PageInfo selectShopListAuditStatus(Page<Shop> page) {
        Integer pageNo = page.getPageNo();
        Integer pageSize = page.getPageSize();
        if (pageNo == null || pageSize == null||pageNo == 0||pageSize == 0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        PageHelper.startPage(pageNo, pageSize);
        Shop data = page.getData();
        //获取当前登录用户ID
        Long userId = ((User) (session.getAttribute("userInfo"))).getUserId();
        if (userDao.checkIsAdmin(userId)>0){// 是管理员
            return new PageInfo<>(shopDao.selectShopListAuditStatus(data));
        }else {// 不是管理员
            return new PageInfo<>(shopDao.selectShopListBindCustomer(userId));
        }
    }

    @Override
    public List<Shop> getAllShops() {
        return shopDao.findAllShops();
    }

    @Override
    public List<ShopStatusCount> getShopStatusCount() {
        return shopDao.countShopsByStatus();
    }

    @Override
    public List<ShopAuditStatusCount> getShopAuditStatusCount() {
        return shopDao.countShopsByAuditStatus();
    }
    @Override
    public Long countShops() {
        return shopDao.countShops();
    }
}
